import React, {useEffect, useLayoutEffect, useRef, useState} from 'react';
import { message, Space} from "antd";
import {Button} from "antd-mobile";
import s from "./code.module.less"
import classNames from "classnames";
import axios from "../../utils/axios";
import {useNavigate} from "react-router";
import copy from 'copy-to-clipboard';
import {LoadingOutlined} from "@ant-design/icons";
const btnProps={
    size:"large",

}
function GetCode() {
    const [phone,setPhone] = useState("")
    const [code,setCode] = useState(""),
        iid = useRef(null),
        [show,setShow]=useState(false),
        [loading,setloading] = useState(false),
        [cdkInfo,setCdkInfo] = useState({}),
        [timer,setTimer]=useState(60);
    const navigate = useNavigate();
    const sid = useRef(null);
    useLayoutEffect(()=>{
        const phoneNumber = sessionStorage.getItem("phoneNumber");
        if(!phoneNumber){
            navigate("/vip/cdk")
        }else{
            setPhone(phoneNumber);
            validate().then(r => {});
        }
    },[navigate]);

    async function validate(replacePhone){
        if(replacePhone){
            setCode("")
            setloading(true)
            try{
                await axios.post("/hlg/replacePhone",{
                    cdk:localStorage.getItem("cdk")
                }).then(res=>{
                    setloading(false)
                    message.success("号码更换成功")
                    sessionStorage.setItem("phoneNumber",res.phone)
                    setPhone(res.phone)
                })
            }catch (err){
                setloading(false)
            }

        }
        setTimer(60);
        iid.current=setInterval(()=>{
            setCode(code=>{
                if (code !==""){
                    setShow(false);
                    clearInterval(iid.current);
                }
                return code;
            })

            setTimer(timer=>{
                if (timer < 2){
                    setShow(true);
                    clearInterval(iid.current)
                }
                return timer-1
            });
        },1000)
    }

    useEffect(()=>{
        axios.get("/app/checkCDK").then(res=>{
        }).catch(()=>{})
        getCode();
        queryCDKType()
        return ()=>{
            clearTimeout(sid.current);
            clearInterval(iid.current)
        }
    },[])
    function queryCDKType(){
        axios.get("/hlg/getCdkType",{
            params:{
                cdk:localStorage.getItem("cdk")
            }
        }).then(res=>{
            if(res.duration > 0){
                setCdkInfo(res);
            }
        })
    }
    const getCode = () => {
        axios.get("/app/getCode").then(res=>{
            if(res.code){
                setCode(res.code);
                setShow(false)
            }
        }).catch(()=>{})
        sid.current=setTimeout(()=>{
            getCode()
        },2000)
    };
    return (
        <div className={classNames(s.wrap,s.scroll)}>
            {
                cdkInfo.type === 2 && <h3>
                    本次消费时长 1 小时，剩余：{cdkInfo.duration} 小时
                </h3>
            }
            <div className={s.card}>
                <header>手机号</header>
                <section>{phone}</section>
                <footer><Button
                    {...btnProps}
                    style={{
                        color:"orange"
                    }}
                    onClick={()=>{
                        copy(phone);
                        message.success("复制成功！")
                    }}
                >复制</Button></footer>
            </div>
            <h2>复制手机号到app或网页登录，在app或网页中点击获取验证码，然后返回本网页等待接收验证码</h2>
            <div className={s.card} style={{backgroundColor:"#00b022"}}>
                <header>验证码</header>
                <section className={code===""?s.shanshuo:""}>{code||"请稍后..."}</section>
                <footer>
                    <Space>
                        {show?"":(timer||"")}<LoadingOutlined />
                        <Button
                            {...btnProps}
                            style={{
                                color:"#00b022"
                            }}
                            onClick={()=>{
                                if(code) {
                                    copy(code);
                                    message.success("复制成功！")
                                }
                            }}
                        >
                            复制
                        </Button>
                    </Space>
                </footer>
            </div>
            <h2>收到验证码后，复制验证码返回app输入验证码登录</h2>
            {
                <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                    <div>已发送验证码，未接收到？</div>
                    <Button color={"primary"} disabled={timer!==0} loading={loading} onClick={validate}>更换手机号{timer===0?"":`(${timer})`}</Button>
                </div>
            }


        </div>
    );
}

export default GetCode;